package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.entity.production.MaMrpOperation;
import com.nuoniu.sibanyun.entity.production.MaMrpOperationDetail;
import com.nuoniu.sibanyun.entity.production.VProductionOrderMain;
import com.nuoniu.sibanyun.mapper.erp.ErpNumberSetMapper;
import com.nuoniu.sibanyun.mapper.production.MaMrpOperationMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpNumberSetService;
import com.nuoniu.sibanyun.service.production.IMaMrpOperationDetailService;
import com.nuoniu.sibanyun.service.production.IMaMrpOperationService;
import com.nuoniu.sibanyun.service.production.IVProductionPlanMainService;
import com.nuoniu.sibanyun.service.so.IVSaleOrderMainService;
import com.nuoniu.sibanyun.service.utils.ErpUtils;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * MRP运算主表 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2023-05-14
 */
@Service
public class MaMrpOperationServiceImpl extends ServiceImpl<MaMrpOperationMapper, MaMrpOperation> implements IMaMrpOperationService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private ErpNumberSetMapper numberSetMapper;
    @Autowired
    private IErpNumberSetService numberSetService;
    @Autowired
    private IMaMrpOperationDetailService maMrpOperationDetailService;
    @Autowired
    private IVSaleOrderMainService saleOrderMainService;
    @Autowired
    private IVProductionPlanMainService productionPlanMainService;

    @Override
    public void saveOrder(MaMrpOperation maMrpOperation) {
        if(maMrpOperation == null) {
            throw new NuoNiuException("数据不能为空");
        }
        if(maMrpOperation.getMaMrpOperationDetailList() == null || maMrpOperation.getMaMrpOperationDetailList().size() == 0) {
            throw new NuoNiuException("单据明细不能为空");
        }

        UserInfo userInfo = UserThreadLocal.get();
        if(maMrpOperation.getId() == null) {
            maMrpOperation.setCompanyId(userInfo.getCompanyId());
            maMrpOperation.setAccountId(accountService.getCurrentAccountId());
            maMrpOperation.setCreateUserId(userInfo.getUserId());
            maMrpOperation.setVoucherCode(getCode());
            maMrpOperation.setVoucherState(-1);
            maMrpOperation.setCreateUserName(userInfo.getRealName());
        }


        Boolean result = this.saveOrUpdate(maMrpOperation);
        if(result) { //保存明细
            List<MaMrpOperationDetail> orderDetailList = maMrpOperation.getMaMrpOperationDetailList();
            List<Long> detailIds = new ArrayList<>();
            orderDetailList.forEach(p -> {
                p.setAccountId(accountService.getCurrentAccountId());
                p.setCompanyId(userInfo.getCompanyId());
                p.setOrderId(maMrpOperation.getId().intValue());
                //添加 不删除的明细ID
                if (p.getId() != null) {
                    detailIds.add(p.getId());
                }
            });

            if (maMrpOperation.getId() != null){
                //删除明细
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("order_id", maMrpOperation.getId());
                if(detailIds != null && detailIds.size() > 0) {
                    wrapper.notIn("id", detailIds);
                }
                maMrpOperationDetailService.remove(wrapper);
            }
            //保存单据明细表
            maMrpOperationDetailService.saveOrUpdateBatch(orderDetailList);

            if(maMrpOperation.getSourceVoucherId() != null && maMrpOperation.getSourceVoucherType() != null) {
                UpdateWrapper wrapper = new UpdateWrapper();
                wrapper.in("id", maMrpOperation.getSourceVoucherId().split(","));
                wrapper.set("is_operation", 1);
                if(maMrpOperation.getSourceVoucherType().equals("MasterProductionSchedule")) {
                    productionPlanMainService.update(wrapper);
                } else {
                    saleOrderMainService.update(wrapper);
                }
            }
        }
    }

    @Override
    public void delete(Long id) {
        if(id == null) {
            throw new NuoNiuException("单据id不能为空");
        }

        MaMrpOperation operation = this.getById(id);
        if(operation != null) {
            this.removeById(id);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("order_id", id);
            maMrpOperationDetailService.remove(wrapper);
            if(operation.getSourceVoucherId() != null && operation.getSourceVoucherType() != null) {
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.in("id", operation.getSourceVoucherId().split(","));
                updateWrapper.set("is_operation", 0);
                if(operation.getSourceVoucherType().equals("MasterProductionSchedule")) {
                    productionPlanMainService.update(updateWrapper);
                } else {
                    saleOrderMainService.update(updateWrapper);
                }
            }
        }

    }

    @Override
    public void submit(Long id, Integer status) {
        if(null == id || null == status || (null != status && (status > 0 || status < -1 )))throw new NuoNiuException("参数错误");
        UserInfo userInfo = UserThreadLocal.get();
        MaMrpOperation main = this.getById(id);
        if(main == null) {
            throw new NuoNiuException("记录不存在");
        }

        /**  统一校验 提交状态 */
        ErpUtils.checkSubmitStatus(main.getVoucherState(), status);

        //提交
        main.setVoucherState(status);
        main.setSubmitDate(LocalDateTime.now());
        main.setSubmitUserId(userInfo.getUserId());
        main.setSubmitUserName(userInfo.getRealName());
        this.updateById(main);
    }

    @Override
    public void examine(Long id, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        MaMrpOperation mrpOperation = new MaMrpOperation();
        mrpOperation.setVoucherState(status);
        mrpOperation.setId(id);
        mrpOperation.setReviewerUserName(userInfo.getRealName());
        mrpOperation.setReviewerUserId(userInfo.getUserId());
        mrpOperation.setReviewerDate(LocalDateTime.now());
        updateById(mrpOperation);
    }


    public String getCode() {
        UserInfo userInfo = UserThreadLocal.get();
        Integer currentAccountId = accountService.getCurrentAccountId();
        ErpNumberSet numberSet = numberSetMapper.getByCode("MrpOperation", userInfo.getCompanyId(), currentAccountId);
        String dateStr = numberSet.getMedian() == 1 ? "%Y-%m-%d" : "%Y-%m";
        String code = baseMapper.getNewestCode(userInfo.getCompanyId(), dateStr);
        return numberSetService.getCode(numberSet, code);
    }
}
